package com.itheima.reggie.controller;


import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;


@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private HttpSession session;

    //@RequestBody只能在对象或map之前
   @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String,String>map){

    //1.接收请求
    String username = map.get("username");
    String password = map.get("password");


    //2.调用service方法登录
     ResultInfo resultInfo =employeeService.login(username,password);


    //3.如果登录成功，将employee保存到session中
    Employee employee = (Employee) resultInfo.getData();
    session.setAttribute("SESSION_EMPLOYEE",employee);

    //4.返回结果
    return resultInfo;
}
//退出

    @PostMapping("/employee/logout")
    public ResultInfo logout() {
        //1. 注销用户的session，
        session.invalidate();

        //2. 返回成功
        return ResultInfo.success(null);
    }

    //员工查询
    @GetMapping("/employee/find")
    public ResultInfo findByName(String name) {
        //1. 调用service查询
        List<Employee> employeeList = employeeService.findByName(name);

        //2. 返回结果
        return ResultInfo.success(employeeList);
    }
    //新增员工：保存员工
    @PostMapping("/employee")//将请求映射到特定的方法
    public ResultInfo save(@RequestBody Employee employee){
       employeeService.save(employee);
       return ResultInfo.success(null);

   }
   //3.查询员工
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id")Long id){
       Employee employee = employeeService.findById(id);
       return ResultInfo.success(employee);

    }
    //4.修改员工
    public ResultInfo update(@RequestBody Employee employee){
       employeeService.update(employee);
       return ResultInfo.success(null);
    }


}
